#!/bin/bash
LANG=en_US.UTF-8

###Check if user is root
if [ $UID -ne 0 ]; then
    echo "Error: You must be root to run this script, please use root to install"
    exit 1
fi

AppDir=/app

#将SD卡扩展至实际容量
/usr/bin/rootfs-expand

#设置时区,启动自动同步时间
timedatectl set-timezone Asia/Shanghai
timedatectl set-ntp yes

#ps -ef|grep nodejs|grep -v grep|awk '{print $2}'|xargs kill -9
#ps -ef|grep mysql|grep -v grep|awk '{print $2}'|xargs kill -9
#ps -ef|grep gosuv|grep -v grep|awk '{print $2}'|xargs kill -9
#ps -ef|grep redis|grep -v grep|awk '{print $2}'|xargs kill -9

function killx()
{
    PROCESS=`ps -ef|grep $1|grep -v grep|grep -v PPID|awk '{print $2}'`
    for i in $PROCESS
    do
    echo "Kill the $1 process [ $i ]"
    kill -9 $i
    done
}

killx nodejs
killx mysql
killx gosuv
killx redis

rm -f /etc/init.d/mysqld
rm -f /etc/systemd/system/gosuv.service 
rm -f /etc/profile.d/mysql.sh
rm -f /etc/profile.d/nodejs.sh
rm -f /etc/profile.d/redis.sh
rm -f /etc/profile.d/go.sh
rm -f /etc/profile.d/app.sh
rm -f /etc/my.cnf
rm -f /usr/local/bin/gosuv
rm -f /tmp/mysql.sock

rm -rf $HOME/.gosuv
rm -rf $AppDir

userdel mysql
userdel nodejs
userdel redis

if [ ! -d "$AppDir" ]; then
    cd /
    mkdir app
    cd app
fi

AppEnvFile=/etc/profile.d/app.sh
echo "export PATH=\$PATH:$AppDir" > $AppEnvFile
source $AppEnvFile

#备份一下,修改CentOS-Base.repo位下面的内容
if [ -f "/etc/yum.repos.d/CentOS-Base.repo" ]; then
    repo=$(cat /etc/yum.repos.d/CentOS-Base.repo|grep mirrors.ustc.edu.cn)
    if [ "${repo}" = "" ];then
        cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak
        curl https://gitee.com/rootsuper/pi4_centos7_repo/raw/master/CentOS-Base.repo -so /etc/yum.repos.d/CentOS-Base.repo --progress
        yum clean all
        yum makecache
    fi
fi

yum -y install gcc gcc-c++ kernel-devel
yum -y install wget git
yum -y update


echo -e "----------------------------------------------------"
echo -e "\033[32m开始安装Golang环境 \033[0m"
echo -e "----------------------------------------------------"

cd $AppDir

GolangEnvFile=/etc/profile.d/go.sh

if [ -d "$AppDir/go" ]; then
    echo -e "\033[31m Golang 已经存在($AppDir/go). \033[0m"
    exit;
fi

if [ -f "$GolangEnvFile" ];then  
    echo -e "\033[31m Golang 环境变量已经存在($NodeJsEnvFile). \033[0m"
    exit;
fi

wget https://dl.google.com/go/go1.13.5.linux-armv6l.tar.gz
tar -zxvf go1.13.5.linux-armv6l.tar.gz
rm -f go1.13.5.linux-armv6l.tar.gz

mkdir -p $HOME/go/pkg $HOME/go/src $HOME/go/bin

cat >> $GolangEnvFile << EOF
export GOROOT=$AppDir/go
export GOPATH=$HOME/go
EOF
cat >> $GolangEnvFile << \EOF
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOROOT/bin:$GOBIN
EOF

source $GolangEnvFile
echo -e "\033[32m Golang 安装成功. \033[0m"



echo -e "----------------------------------------------------"
echo -e "\033[32m开始安装NodeJs环境 \033[0m"
echo -e "----------------------------------------------------"

cd $AppDir

NodeJsEnvFile=/etc/profile.d/nodejs.sh

if [ -d "$AppDir/nodejs" ]; then
    echo -e "\033[31m nodejs 已经存在($AppDir/nodejs). \033[0m"
    exit;
fi

if [ -f "$NodeJsEnvFile" ];then  
    echo -e "\033[31m nodejs 环境变量已经存在($NodeJsEnvFile). \033[0m"
    exit;
fi

wget https://npm.taobao.org/mirrors/node/v9.11.2/node-v9.11.2-linux-armv7l.tar.gz
tar -zxvf node-v9.11.2-linux-armv7l.tar.gz
mv node-v9.11.2-linux-armv7l $AppDir/nodejs
rm -f node-v9.11.2-linux-armv7l.tar.gz
#echo "export PATH=$PATH:$AppDir/nodejs/bin" > $NodeJsEnvFile

cat >> $NodeJsEnvFile << EOF
export NODEJS=$AppDir/nodejs
EOF
cat >> $NodeJsEnvFile << \EOF
export PATH=$PATH:$NODEJS/bin
EOF

source $NodeJsEnvFile
echo -e "\033[32m nodejs 安装完成. \033[0m"

echo -e "----------------------------------------------------"
echo -e "\033[32m开始安装 Mysql 5.7.28 环境 \033[0m"
echo -e "----------------------------------------------------"

cd $AppDir

MysqlEnvFile=/etc/profile.d/mysql.sh

MysqlInstall=$AppDir/mysql
MysqlDataBase=$AppDir/data/mysql
MysqlDataDir=$AppDir/data/mysql/data
MysqlLogdir=$AppDir/data/mysql/logs
MysqlConfig=/etc/my.cnf

if [ -d "$MysqlInstall" ]; then
    echo -e "\033[31m Mysql 5.7.28 已经安装过了($MysqlInstall). \033[0m"
    exit;
fi

if [ -f "$MysqlEnvFile" ];then  
    echo -e "\033[31m Mysql 5.7.28 环境变量已经存在($MysqlEnvFile). \033[0m"
    exit;
fi

wget https://raspberry-pi4.oss-cn-shenzhen.aliyuncs.com/mysql5.7.28.tar.gz
tar -zxvf mysql5.7.28.tar.gz
rm -f mysql5.7.28.tar.gz

if [ ! -d "$MysqlDataDir" ]; then 
    mkdir -p  $MysqlDataDir
fi

if [ ! -d "$MysqlLogdir" ]; then 
    mkdir -p  $MysqlLogdir
fi

useradd mysql -s /sbin/nologin -M

chown -R mysql:mysql $MysqlDataBase
chown -R mysql:mysql $MysqlInstall

if [ -f "$MysqlConfig" ]; then
    mv $MysqlConfig $MysqlConfig.`date +%Y%m%d%H%M%S`.bak
fi

cat > $MysqlConfig <<EOF

[client]
#password	= your_password
port		= 3306
socket		= /tmp/mysql.sock

[mysql]
no-auto-rehash

[mysqld]
port		= 3306
socket		= /tmp/mysql.sock
datadir = $MysqlDataDir
default_storage_engine = InnoDB
performance_schema_max_table_instances = 400
table_definition_cache = 400
skip-external-locking
key_buffer_size = 64M
max_allowed_packet = 100G
table_open_cache = 256
sort_buffer_size = 1M
net_buffer_length = 4K
read_buffer_size = 1M
read_rnd_buffer_size = 256K
myisam_sort_buffer_size = 16M
thread_cache_size = 32
query_cache_size = 32M
tmp_table_size = 64M
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

explicit_defaults_for_timestamp = true
#skip-name-resolve
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535

log-bin=mysql-bin
binlog_format=mixed
server-id = 1
expire_logs_days = 10
slow_query_log=1
slow-query-log-file=$MysqlDataDir/mysql-slow.log
long_query_time=3
#log_queries_not_using_indexes=on
early-plugin-load = ""

log_error=$MysqlLogdir/error.log


innodb_data_home_dir = $MysqlDataDir
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = $MysqlDataDir
innodb_buffer_pool_size = 256M
innodb_log_file_size = 128M
innodb_log_buffer_size = 32M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50
innodb_max_dirty_pages_pct = 90
innodb_read_io_threads = 4
innodb_write_io_threads = 4

[mysqldump]
quick
max_allowed_packet = 500M

[myisamchk]
key_buffer_size = 64M
sort_buffer_size = 1M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout
EOF

yum install libaio-devel -y

echo -e "\033[32m 正在初始化Mysql..... \033[0m"
$MysqlInstall/bin/mysqld --initialize --user=mysql --basedir=$MysqlInstall  --datadir=$MysqlDataDir
echo -e "\033[32m 初始化Mysql完成..... \033[0m"

password=$(grep 'A temporary password' $MysqlLogdir/error.log |awk  '{print $NF}')

echo -e "\033[32m 正在安装Mysql系统服务..... \033[0m"

cp $MysqlInstall/support-files/mysql.server /etc/init.d/mysqld

chkconfig --add mysqld
chkconfig --list mysqld
chkconfig mysqld on

echo -e "\033[32m Mysql系统服务安装完成..... \033[0m"

echo -e "\033[32m 正在启动Mysql系统服务..... \033[0m"

/etc/init.d/mysqld start

#echo "export PATH=$PATH:$MysqlInstall/bin" > $MysqlEnvFile
cat >> $MysqlEnvFile << EOF
export MYSQL=$MysqlInstall
EOF
cat >> $MysqlEnvFile << \EOF
export PATH=$PATH:$MYSQL/bin
EOF

source $MysqlEnvFile


MysqlRootPwd=`cat /dev/urandom | head -n 16 | md5sum | head -c 10`

$MysqlInstall/bin/mysqladmin -uroot -p"$password" password $MysqlRootPwd

echo -e "\033[32m 正在开启Mysql远程访问...... \033[0m"

mysql -uroot -p"$MysqlRootPwd" -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '$MysqlRootPwd';"
mysql -uroot -p"$MysqlRootPwd" -e "flush privileges;"

/etc/init.d/mysqld stop
/etc/init.d/mysqld start

echo -e "\033[32m Mysql远程访问开启成功 \033[0m"

echo -e "\033[32m Mysql 5.7.28 安装完成 \033[0m"




echo -e "----------------------------------------------------"
echo -e "\033[32m开始安装Redis 5.0.5 \033[0m"
echo -e "----------------------------------------------------"

cd $AppDir

RedisEnvFile=/etc/profile.d/redis.sh

if [ -f "$AppDir/redis/redis-server" ]; then
    echo -e "\033[31mRedis 5.0.5 已经安装过了($AppDir/redis/redis-server). \033[0m"
    exit;
fi

mkdir redis

wget https://raspberry-pi4.oss-cn-shenzhen.aliyuncs.com/redis-server.tar.gz
tar -zxvf redis-server.tar.gz -C $AppDir/redis
rm -f redis-server.tar.gz
useradd redis -s /sbin/nologin -M
chown -R redis:redis $AppDir/redis

#echo "export PATH=$PATH:$AppDir/redis" > $RedisEnvFile
cat >> $RedisEnvFile << EOF
export REDIS=$AppDir
EOF
cat >> $RedisEnvFile << \EOF
export PATH=$PATH:$REDIS/redis
EOF

source $RedisEnvFile

echo -e "\033[32mRedis 5.0.5 安装完成. \033[0m"


echo -e "----------------------------------------------------"
echo -e "\033[32m开始安装GoSUV进程管理工具 \033[0m"
echo -e "----------------------------------------------------"

cd $AppDir

if [ -d "$HOME/.gosuv" ]; then
    echo -e "\033[31mGoSUV 已经安装过了,配置文件($HOME/.gosuv). \033[0m"
    exit;
fi

if [ -f "$AppDir/gosuv" ]; then
    echo -e "\033[31mGoSUV 已经安装过了($AppDir/gosuv). \033[0m"
    exit;
fi

wget https://raspberry-pi4.oss-cn-shenzhen.aliyuncs.com/gosuv_linux_armv7.tar.gz
tar -zxvf gosuv_linux_armv7.tar.gz
rm -f gosuv_linux_armv7.tar.gz

gosuvpwd=`cat /dev/urandom | head -n 16 | md5sum | head -c 6`

mkdir -p $HOME/.gosuv/conf
touch $HOME/.gosuv/conf/config.yml
touch $HOME/.gosuv/conf/programs.yml

cat > $HOME/.gosuv/conf/config.yml <<EOF
server:
  httpauth:
    enabled: true
    username: admin
    password: $gosuvpwd
  addr: :12345
  name: ""
  master: ""
client:
  server_url: http://admin:$gosuvpwd@localhost:12345
EOF

cat > $HOME/.gosuv/conf/programs.yml <<EOF
- name: redis
  command: ./redis-server ./redis.conf
  environ: []
  directory: $AppDir/redis
  start_auto: true
  start_retries: 3
  start_seconds: 3
  stop_timeout: 3
  user: redis
EOF

cat > /etc/systemd/system/gosuv.service << EOF
[Unit]
Description=gosuv
After=syslog.target
After=network.target

[Service]
Type=simple
User=root
ExecStart=/app/gosuv start-server -f
Restart=always

ProtectSystem=full
PrivateDevices=yes
PrivateTmp=yes
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start gosuv
systemctl enable gosuv

echo -e "\033[32mGoSUV 安装完成,已经启动. \033[0m"

source /etc/profile

firewall-cmd --zone=public --add-port=6379/tcp --permanent
firewall-cmd --zone=public --add-port=3306/tcp --permanent
firewall-cmd --zone=public --add-port=12345/tcp --permanent
firewall-cmd --reload

HOST_IP=$(/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6 | awk '{print $2}' | tr -d "addr:")

echo -e "=================================================================="
echo -e "\033[32m 恭喜你! 全部安装完成咯! \033[0m"
echo -e "=================================================================="
echo -e "Golang 当前版本: \033[32m$(go version)\033[0m"
echo -e "Nodejs 当前版本: \033[32m$(node -v)\033[0m"
echo -e "Mysql  当前版本: \033[32m$(mysql -V)\033[0m"
echo -e "Mysql  默认密码: \033[31m$MysqlRootPwd\033[0m"
echo -e "GoSUV Web Site: \033[32mhttp://$HOST_IP:12345\033[0m"
echo -e "GoSUV Web User: \033[32madmin\033[0m"
echo -e "GoSUV Web Pass: \033[32m$gosuvpwd\033[0m"
echo -e "\033[33m注意:请保存好相关密码信息\033[0m"
echo -e "=================================================================="